/*
  This file is part of jTopaz.
  http://gcl.cis.udel.edu/projects/jtopaz
  Copyright (C) 2009 University of Delaware

  jTopaz is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  jTopaz is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of                                                        
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with jTopaz.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
  Contains methods that should be running in the background while the extension is running.
  -daemon() runs the whole time, checks that the user has connected.  Then checks if a job has finished, if so it updates the queue.  if a job is in progress gets the speed/progres and updates the queue.
*/
var username;
var passwd;
var myProxyServer;
var client;
var waitWhenQueueReady=0;
var listContents;
var transferCount = 0;
var currentTransfer=-1;
var lastUpdated=0;
var infoClientStarted=false;
var transferClientStarted=false;
var uploadClientStarted=false;
var loginDone=false;

/*
  daemon function, this should be running in the background the entire time the page is loaded
*/
function daemon() {
 
    //alert("daemon still running?");
    //load the component
    var applet = window.frames.appletFrame;
    
    var appletFrame = document.getElementById("appletFrame");
    
    //alert(appletFrame.getAttribute("src"));
    if (appletFrame.getAttribute("src") == "") {
	setTimeout("daemon()", 1000);
	return;
    }
  		
    
    //if not done logging in
    //alert("Connected ? " + applet.isConnected());
    //if (true) {
    if (!applet.isConnected() ) {
    	if ((applet.isInfoReady()) && (!infoClientStarted)) {
	    infoClientStarted=true;
    	}
   
	if (applet.transferCanceled()) {
	    //alert("trying to reconnect");
	    applet.reconnectTransfer();
	}
   		
    	if (applet.isTransferReady()) {

	    //alert("trying to set transfer client");
	    //set the transfer client
	    applet.setTransferClient();
	    transferClientStarted=true;
    		
	    //enable the button
	    var dlButton = document.getElementById("download");
	    dlButton.setAttribute("disabled", false);
    		
    	}
    
    	if (applet.isUploadReady()) {
	    //set the upload client
	    applet.setUploadClient();
	    uploadClientStarted = true;
    		
	    //enable the button	
	    var upButton = document.getElementById("upload");
	    upButton.setAttribute("disabled", false);
    		
    	}
    
    	//once all three are done
    	if (infoClientStarted && transferClientStarted && uploadClientStarted){
	    var disconBut = document.getElementById("disconnect");
	    disconBut.setAttribute("disabled", false);
	    var conBut = document.getElementById("connect");
	    conBut.setAttribute("disabled", true);
	    loginDone=true;
    		
	    applet.setConnected(true);
	    //reset these as null for the next transfer
	    infoClientStarted=false;
	    transferClientStarted=false;
	    uploadClientStarted=false;
    	}
    }

	
    //find out if a job is in progress
    var inProgress = applet.transferInProgress();
    	
    //if so
    if(inProgress) {
	
	//get speed/progress/name
	var speed = applet.getSpeed();
	var progress = applet.getProgress();
	var name = applet.getTransferName();

	speed = (speed/1024)*8;

	//update the transfer with the new values
	updateDownload(name, speed, progress);
    }
	
    //otherwise if a job is ready
    //let daemon run twice more... otherwise queued download will fail - not sure why yet
    else if (applet.queueReady() && waitWhenQueueReady==2){
	waitWhenQueueReady=0;
	cleanUpQueue();
	currentTransfer = currentTransfer+1;
	//start the next transfer
	applet.StartTransfer();
    }
		
	
    //otherwise just clean up the queue	
    else {
	if(applet.queueReady()){
	    waitWhenQueueReady=waitWhenQueueReady+1;
	}
	cleanUpQueue();	
    }
 
    //rerun the daemon in a second
    setTimeout("daemon()", 1000);
}

/*
  cleans up the queue.  if a job is done set it as complete
*/
function cleanUpQueue() {

    var applet = window.frames.appletFrame;

    //get the name of the last completed transfer                           
    var last = applet.getLastCompletedTransfer();
    
	
    //if nothing done, return
    if (last == null) {
	return;
    }

    //check to make sure it matches what's here (need to change this)
    if (last[1] == lastUpdated) {
	//update the download with 100% and complete
	updateDownload(last[0], "complete", "100");
	clear("remoteContents");
	clear("localContents");
	displayContents();
	lastUpdated = lastUpdated + 1;
		
    }
}

function formatNums(num){
    if (num>100){
	return Math.round(num);
    }
    else if (num>10){
	return Math.round(num*10)/10;
    }
    else if (num>0) {
	return Math.round(num*100)/100;
    }
    else {
	return num;
    }
}

/*
  updates the transfer in the queue with the current info
*/
function updateDownload(name, speed, progress) {
    //don't display a billion decimal places
    if(speed!="complete"){
	speed = formatNums(speed);
    }
    progress = formatNums(progress);

    //get the row
    var rows = document.getElementsByAttribute("id", name + " downloadRow");
	
    for(var i=0; i<rows.length; i++) {

	var theRow = rows[i];
	
	//need to have this check in here because multiple transfers can have the same filename.
	if (theRow.getAttribute("value") != currentTransfer) {

	}
	
	else {
		
	    //update the info, and append it
	    var oldLabel2 = theRow.childNodes[1];
	    if (oldLabel2.getAttribute("label") == "Cancelled") {
			
		return;	
	    }
		
	    var nodes = theRow.childNodes;
		
	    var newLabel2 = document.createElement("treecell");
	    newLabel2.setAttribute("id", name + " label2");
	    if(speed!="complete"){
		newLabel2.setAttribute("label", speed);
	    }
	    else {
		newLabel2.setAttribute("label", speed);
	    }
	    theRow.replaceChild(newLabel2, nodes[1]);
		
		
	    var newLabel3 = document.createElement("treecell");
	    newLabel3.setAttribute("id", name + " label3");
	    newLabel3.setAttribute("label", progress + "%");
		
	    theRow.replaceChild(newLabel3, nodes[2]);
		
	    //create a new meter, and replace it
	    var newMeter = document.createElement("treecell");
	    newMeter.setAttribute("id", name + " meter");
	    newMeter.setAttribute("mode", "normal");
	    newMeter.setAttribute("value", progress);
	    theRow.replaceChild(newMeter, nodes[3]);	
	}
    }
}
